// ===============================================
// core_cupertino_assets
//
// Create by Will on 8/4/2024 00:42
// Copyright Will.All rights reserved.
// ===============================================

import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';

import '../../const/app_enum.dart';
import '../../const/app_policies.dart';
import '../../themes/app_default_style.dart';
import '../core_intl/core_kit_localizations.dart';

class CoreCupertinoAssets {
  CoreCupertinoAssets._internal();

  static Future<List<AssetEntity>?> showCupertinoActionSheet(
    BuildContext context, {
    required List<AssetEntity> selectedAssets,
    int maxPic = AppPolicies.maxPic,
    RequestType requestType = RequestType.image,
  }) async {
    return showCupertinoModalPopup<List<AssetEntity>?>(
      context: context,
      builder: (context) {
        return ScrollConfiguration(
          behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
          child: Semantics(
            namesRoute: true,
            scopesRoute: true,
            explicitChildNodes: true,
            label: 'Alert',
            child: CupertinoUserInterfaceLevel(
              data: CupertinoUserInterfaceLevelData.elevated,
              child: SizedBox(
                width: double.infinity,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: <Widget>[
                    InkWell(
                      onTap: () async {
                        final selected = await getPermission(
                          context,
                          selectedAssets: selectedAssets,
                          permission: Permission.photos,
                          maxPic: maxPic,
                          requestType: requestType,
                        );
                        if (!context.mounted) {
                          return;
                        }
                        Navigator.of(context).pop<List<AssetEntity>?>(selected);
                      },
                      child: Container(
                        height: 50,
                        alignment: Alignment.center,
                        color: CupertinoTheme.of(context).barBackgroundColor,
                        child: Text(
                          CoreKitS.of(context).album,
                        ),
                      ),
                    ),
                    const Divider(
                      height: 1,
                    ),
                    InkWell(
                      onTap: () async {
                        final selected = await getPermission(
                          context,
                          selectedAssets: selectedAssets,
                          permission: Permission.camera,
                          maxPic: maxPic,
                          requestType: requestType,
                        );
                        if (!context.mounted) {
                          return;
                        }
                        Navigator.of(context).pop<List<AssetEntity>?>(selected);
                      },
                      child: Container(
                        height: 50,
                        alignment: Alignment.center,
                        color: CupertinoTheme.of(context).barBackgroundColor,
                        child: Text(
                          CoreKitS.of(context).camera,
                        ),
                      ),
                    ),
                    Container(
                      height: appStylePadding,
                      color: Theme.of(context).dividerColor,
                    ),
                    InkWell(
                      onTap: () => Navigator.of(context).pop(),
                      child: Container(
                        height: 50,
                        alignment: Alignment.center,
                        color: CupertinoTheme.of(context).barBackgroundColor,
                        child: Text(
                          CoreKitS.of(context).cancel,
                        ),
                      ),
                    ),
                    Container(
                      height: MediaQuery.paddingOf(context).bottom,
                      color: CupertinoTheme.of(context).barBackgroundColor,
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  static Future<List<AssetEntity>?> getPermission(
    BuildContext context, {
    required List<AssetEntity> selectedAssets,
    required Permission permission,
    required int maxPic,
    RequestType requestType = RequestType.image,
  }) async {
    var value = await permission.request();
    //因为Android 的照片不是像ios那样 他是使用 storage 存储的概念
    if (Platform.isAndroid) {
      final deviceInfo = DeviceInfoPlugin();
      final androidInfo = await deviceInfo.androidInfo;
      final sdkInt = androidInfo.version.sdkInt;

      //只要是 小于sdk 32 的 Android 13以下的 都是走storage 不管是视频 还是拍照
      //上面 的权限 就是标准的做法
      if (sdkInt <= 32) {
        value = await Permission.storage.request();
      }
    }

    var content = '';
    if (value == PermissionStatus.granted) {
      var photoType = PickerPhotoType.album;
      if (permission == Permission.photos) {
        photoType = PickerPhotoType.album;
      }
      if (permission == Permission.camera) {
        photoType = PickerPhotoType.camera;
      }
      if (permission == Permission.videos) {
        photoType = PickerPhotoType.video;
      }

      if (!context.mounted) {
        return null;
      }
      return pickPhotos(
        context,
        selectedAssets: selectedAssets,
        pickerPhotoType: photoType,
        maxPic: maxPic,
        requestType: requestType,
      );
    } else {
      if (permission == Permission.photos) {
        content = CoreKitS.of(context).permissionPhotosClose;
      }
      if (permission == Permission.camera) {
        content = CoreKitS.of(context).permissionCameraClose;
      }
      if (!context.mounted) {
        return null;
      }
      await showCupertinoAlertDialog(context, content: content);
    }
    return null;
  }

  static Future<void> showCupertinoAlertDialog(
    BuildContext context, {
    required String content,
    String? cancelText,
    VoidCallback? callback,
    bool closeAlert = true,
  }) {
    return showCupertinoDialog(
      context: context,
      builder: (context) {
        return CupertinoAlertDialog(
          title: Text(CoreKitS.of(context).dialogTitlePermissionRequired),
          content: Text(content),
          actions: <Widget>[
            CupertinoDialogAction(
              child: Text(CoreKitS.of(context).dialogTitlePermissionSettings),
              onPressed: () {
                openAppSettings(); //打开设置页面
                Navigator.of(context).pop();
              },
            ),
            CupertinoDialogAction(
              isDestructiveAction: true,
              onPressed: () {
                Navigator.of(context).pop();
                callback?.call();
              },
              child: Text(CoreKitS.of(context).cancel),
            ),
          ],
        );
      },
    );
  }

  static Future<List<AssetEntity>?> pickPhotos(
    BuildContext context, {
    required List<AssetEntity> selectedAssets,
    required PickerPhotoType pickerPhotoType,
    required int maxPic,
    RequestType requestType = RequestType.image,
  }) async {
    if (pickerPhotoType == PickerPhotoType.album ||
        pickerPhotoType == PickerPhotoType.video) {
      final assets = await AssetPicker.pickAssets(
        context,
        pickerConfig: AssetPickerConfig(
          selectedAssets: selectedAssets,
          maxAssets: selectedAssets.length >= maxPic
              ? maxPic
              : maxPic - selectedAssets.length,
          requestType: requestType,
          themeColor: CupertinoTheme.of(context).primaryColor,
        ),
      );

      if (assets != null) {
        return selectedAssets = assets;
      }
      return null;
    } else {
      await Future<void>.delayed(const Duration(milliseconds: 200));

      final assets = await CameraPicker.pickFromCamera(context);

      if (assets != null) {
        return selectedAssets = <AssetEntity>[assets];
      }
      return null;
    }
  }

  // void clear() {
  //   return selectedAssets.clear();
  // }
}
